package com.proxy;

import com.database.common.Service;
import com.database.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-03-04.
 *
 * @author zhoufy
 */

@Service
public class TransactionProxyUtil {


    private TransactionManager transactionManager;


    public Object getProxyObject(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Object resultObj = null;
                transactionManager.beginTransaction();
                try {
                    resultObj = method.invoke(obj, args);
                    transactionManager.commit();
                } catch (Exception e) {
                    transactionManager.rollback();
                }
                return resultObj;
            }
        });
    }
}
